﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.IO;
using System.Management;
using System.Security.Principal;

namespace InfoPathDebugger
{
    public class InfoPathFormHelper
    {
        public static void ClearInfoPathCache()
        {
            // If the InfoPath cache folder exists, delete all files in it.
            if (Directory.Exists(INFOPATH_FORM_CACHE_PATH))
            {
                String[] allFilePaths = Directory.GetFiles(INFOPATH_FORM_CACHE_PATH, "*.*", SearchOption.AllDirectories);
                foreach (String filePath in allFilePaths)
                {
                    File.SetAttributes(filePath, FileAttributes.Normal);
                    File.Delete(filePath);
                }

                Directory.Delete(INFOPATH_FORM_CACHE_PATH, true);

                //// Delete all sub directories.
                //String[] dirPaths = Directory.GetDirectories(INFOPATH_FORM_CACHE_PATH);
                //foreach (String dirPath in dirPaths)
                //{
                //    //Directory.Delete(dirPath, true);
                //    String dirObject = String.Format("win32_Directory.Name='{0}'", dirPath);
                //    using (ManagementObject dir = new ManagementObject(dirObject))
                //    {
                //        dir.Get();
                //        ManagementBaseObject outParams = dir.InvokeMethod("Delete", null, null);

                //        // Return value should be 0, else failure
                //        if (Convert.ToInt32(outParams.Properties["ReturnValue"].Value) != 0)
                //        {
                //            throw new FieldAccessException(String.Format("Can't delete all cache files of InfoPath. Please locate to '{0}' to delete all files and folders.", INFOPATH_FORM_CACHE_PATH));
                //        }
                //    }
                //}

                //// Delete all files.
                //String[] filePaths = Directory.GetFiles(INFOPATH_FORM_CACHE_PATH);
                //foreach (String filePath in filePaths)
                //{
                //    File.SetAttributes(filePath, FileAttributes.Normal);
                //    File.Delete(filePath);
                //}
            }
        }

        /// <summary>
        /// Modify the mso-infoPathSolution href="xxx" to href="{xsn file path}".
        /// </summary>
        /// <param name="templateFilePath">The path of the template file.</param>
        public static void ModifyTemplateFile(String templateFilePath, String xsnFilePath)
        {
            // Read the template contents.
            StreamReader sr = new StreamReader(templateFilePath);
            String orgTemplateContent = sr.ReadToEnd();
            sr.Close();

            Int32 msoStartIndex = orgTemplateContent.IndexOf("<?mso-infoPathSolution");
            Int32 msoEndIndex = orgTemplateContent.IndexOf("?>", msoStartIndex);

            Int32 indexHref = orgTemplateContent.IndexOf("href=\"", msoStartIndex, msoEndIndex - msoStartIndex + 1);
            Int32 indexHrefEndQuote = orgTemplateContent.IndexOf("\"", indexHref + 6);

            String destTemplateContent = String.Empty;
            if (indexHref != -1)
            {
                destTemplateContent = orgTemplateContent.Remove(indexHref, indexHrefEndQuote - indexHref + 1);
                destTemplateContent = destTemplateContent.Insert(indexHref, String.Format("href=\"{0}\"", xsnFilePath));
            }
            else
            {
                indexHref = orgTemplateContent.IndexOf("<?mso-infoPathSolution", StringComparison.OrdinalIgnoreCase);
                destTemplateContent = orgTemplateContent.Insert(indexHref + 22, String.Format(" href=\"{0}\" ", xsnFilePath));
            }

            // Write back to the template file.
            StreamWriter sw = new StreamWriter(templateFilePath);
            sw.Write(destTemplateContent);
            sw.Close();
        }

        private static readonly String INFOPATH_FORM_CACHE_PATH = System.Environment.GetFolderPath(System.Environment.SpecialFolder.LocalApplicationData) + @"\Microsoft\InfoPath\FormCache2";
    }
}
